package com.dongdongshop.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.dongdongshop.admin.model.TbOrder;
import com.dongdongshop.admin.model.TbOrderItem;
import com.dongdongshop.api.CartServiceApi;
import com.dongdongshop.api.GoodsServiceApi;
import com.dongdongshop.api.LoginUserServiceApi;
import com.dongdongshop.common.Result;
import com.dongdongshop.constant.CacheConstant;
import com.dongdongshop.dto.AddrDTO;
import com.dongdongshop.dto.CartDTO;
import com.dongdongshop.dto.CartDetailDTO;
import com.dongdongshop.dto.ItemDTO;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional//本地事务注解
@GlobalTransactional(rollbackFor = Exception.class)//添加全局事务注解
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private LoginUserServiceApi loginUserServiceApi;
   @Autowired
   private CartServiceApi cartServiceApi;
   @Autowired
   private GoodsServiceApi goodsServiceApi;
   @Autowired
   private RedisTemplate redisTemplate;
    @Override
    public void createOrder(Long addrId, Integer payType, String autharizeToken) {
        //根据地址的id去查询出详细信息
        Result<AddrDTO> result = loginUserServiceApi.getAddrById(addrId);
        if (result.getCode()!=10000) {
            throw new RuntimeException("收货地址不存在");
        }
        //获取收货地址
        AddrDTO addr = result.getData();

        //直接调用购物车服务查询购物车
        Result<List<CartDTO>> cartDTOResult = cartServiceApi.selectCart(autharizeToken);
        if(cartDTOResult.getCode()!=10000){
            throw new RuntimeException("购物车为空");
        }
        List<CartDTO> data1 = cartDTOResult.getData();
        //3创建订单
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        List<TbOrder> orderList = new ArrayList();
        List<TbOrderItem> tbOrderItemList = new ArrayList();
        //库存
        List<ItemDTO> itemDTOList = new ArrayList();
        for (CartDTO cartDTO : data1) {
            TbOrder tbOrder = new TbOrder();
            //创建订单id
            long orderId = snowflake.nextId();
            tbOrder.setOrderId(orderId);//主键
            tbOrder.setBuyerNick(addr.getContact());
            tbOrder.setCreateTime(new Date());
            tbOrder.setBuyerRate("0");//未评价
            tbOrder.setUserId(addr.getUserId());
            List<CartDetailDTO> cartDetailVOList = cartDTO.getCartDetailVOList();
            BigDecimal sumMony = new BigDecimal(0);
            for (CartDetailDTO detailDTO : cartDetailVOList) {
                sumMony = sumMony.add(detailDTO.getTotalMoney());
                TbOrderItem tbOrderItem = new TbOrderItem();
                tbOrderItem.setGoodsId(detailDTO.getItemId());
                long l = snowflake.nextId();
                tbOrderItem.setId(l);
                tbOrderItem.setItemId(detailDTO.getItemId());
                tbOrderItem.setNum(detailDTO.getNum());
                tbOrderItem.setOrderId(orderId);
                tbOrderItem.setPrice(detailDTO.getPrice());
                tbOrderItem.setPicPath(detailDTO.getImage());
                tbOrderItem.setSellerId(detailDTO.getSellerId());
                tbOrderItem.setTitle(detailDTO.getTitle());
                tbOrderItem.setTotalFee(detailDTO.getTotalMoney());
                tbOrderItem.setStatus(payType.toString());
                tbOrderItemList.add(tbOrderItem);
                //扣减库存需要的数据
                ItemDTO item = new ItemDTO();
                item.setId(detailDTO.getItemId());
                item.setNum(detailDTO.getNum());
                itemDTOList.add(item);
            }
            tbOrder.setPayment(sumMony);
            //收货人
            tbOrder.setReceiver(addr.getContact());
            //支付类型
            tbOrder.setPaymentType(payType.toString());
            tbOrder.setReceiverAreaName(addr.getAddress());
            tbOrder.setReceiverMobile(addr.getMobile());
            //重要
            tbOrder.setSellerId(cartDTO.getSellerId());
            tbOrder.setStatus("1");//待支付
            orderList.add(tbOrder);

        }
        try {
            // feign接口扣减库存
            goodsServiceApi.subStockCount(itemDTOList);
            //保存订单
            orderMapper.insertOrderList(orderList);
            /*int x = 9/0;*/
            //保存明细
            orderMapper.inserttbOrderItemList(tbOrderItemList);
            //删除redis缓存
            redisTemplate.delete(CacheConstant.CART_CACHE_PREFIX + addr.getUserId());
        }catch (Exception e) {
            throw e;
        }

    }
}
